/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.utils;

import java.util.Date;
import java.util.Vector;

/**
* Used by log to maintain a new ID per thread
*/
public class ThreadId {
	static Vector thread_ids=new Vector();

	private Thread thread;
	private long id;
	private Date last_accessed=new Date();

	ThreadId(Thread p_thread){
		thread=p_thread;
		id=getNextId();
	}

	static private long getNextId(){
		long next_id=Settings.getLong("Logging.NextThreadId",0);
		Settings.setLong("Logging.NextThreadId",next_id+1);
		Settings.save();
		return next_id;
	}

	long getId(){
		last_accessed=new Date();
		return id;
	}

	boolean isForThread(Thread p_thread){
		return p_thread==thread;
	}

	boolean isPossiblyDead(Date was_last_accessed){
		return last_accessed.compareTo(was_last_accessed)<=0;
	}

	static ThreadId findThreadId(Thread thread){
		for (int t=0;thread!=null && t<thread_ids.size();t++){
			ThreadId id=(ThreadId)thread_ids.get(t);
			if (id.isForThread(thread)){
				return id;
			}
		}
		return null;
	}

	public static long getCurrentId(){
		// Add new
		ThreadId id=findThreadId(Thread.currentThread());
		if (id==null){
			id=new ThreadId(Thread.currentThread());
			thread_ids.add(id);
		}
		return id.getId();
	}

	public static void removeThread(){
		ThreadId id=findThreadId(Thread.currentThread());
		if (id!=null){
			thread_ids.remove(id);
		}
	}
}

